package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.admin.entity.AdChannel;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.service.AdChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exceptions.LeadnewsException;
import com.heima.common.util.BeanHelper;
import com.heima.model.admin.dtos.ChannelDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;


/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2021-03-31
 */
@Service
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper, AdChannel> implements AdChannelService {

    @Autowired
    private AdChannelMapper adChannelMapper;
    /**
     * @Author: fuzihang
     * @Date: 19:00 2021/3/31
     * @Parms [channelDto]
     * @ReturnType: com.heima.common.dtos.PageResult<com.heima.model.admin.dtos.ChannelDto>
     * @Description: 分页查询 频道
    */
    @Override
    public PageResult<ChannelDto> findByPage(ChannelDto dto) {
//        设置分页条件
        Page<AdChannel> page = new Page<>(dto.getPage(), dto.getSize());
//        设置查询条件
//        select * from ad_channel where name like '%?%'
        QueryWrapper<AdChannel> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(dto.getName())){
//            queryWrapper.like("name",dto.getName());
            queryWrapper.lambda().like(AdChannel::getName,dto.getName());
        }

//        分页查询
        IPage<AdChannel> adChannelIPage = page(page, queryWrapper);
//        判断
        if(CollectionUtils.isEmpty(adChannelIPage.getRecords())){
            throw new LeadnewsException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        对象转换,BeanUtils
        List<ChannelDto> channelDtoList = BeanHelper.copyWithCollection(adChannelIPage.getRecords(), ChannelDto.class);
//        构造分页对象返回
        return new PageResult(dto.getPage(),dto.getSize(),adChannelIPage.getTotal(),channelDtoList);
    }

}
